<?php

namespace apiend\modules\shop\controllers;

use Yii;
use apiend\components\Controller;
use apiend\modules\shop\models\OrderPlaceForm;
use apiend\modules\shop\models\OrderReceiveForm;
use apiend\modules\shop\models\OrderCancelForm;
use apiend\modules\shop\models\OrderView;
use apiend\modules\shop\models\OrderSearch;

/**
 * 订单相关接口
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderController extends Controller {

    /**
     * 订单检索模型
     * @inheritdoc
     */
    public $modelClass = OrderSearch::class;

    /**
     * Declares the allowed HTTP verbs.
     * Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
     * @return array the allowed HTTP verbs.
     */
    protected function verbs() {
        return [
            'index' => ['GET'],
            'view' => ['GET'],
            '*' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions() {
        return [
            'view' => [
                'class' => 'yii\rest\ViewAction',
                'modelClass' => OrderView::class
            ],
        ];
    }

    /**
     * 订单列表
     * @return mixed
     */
    public function actionIndex() {
        /* @var $modelClass \apiend\modules\shop\models\OrderSearch */
        $model = new $this->modelClass;
        $model->user_id = $this->uid;
        $model->load(Yii::$app->request->getQueryParams(), '');
        return $model->search();
    }

    /**
     * 统一下单
     * @return mixed
     */
    public function actionCreate() {
        $model = new OrderPlaceForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('订单创建失败');
        }
        return $model->save();
    }

    /**
     * 取消订单
     * @return mixed
     */
    public function actionCancel() {
        $model = new OrderCancelForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('订单取消失败');
        }
        return $model->save();
    }

    /**
     * 确认收货
     * @return mixed
     */
    public function actionReceive() {
        $model = new OrderReceiveForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('订单确认收货保存失败');
        }
        return $model->save();
    }

}
